/**
 * @file ai_computer_terminal.cpp
 * @brief Implementation of AI to computer terminal
 */

#include "ai_computer_terminal.h"
#include <wx/filename.h>
#include <wx/dir.h>
#include <wx/tokenzr.h>

AIComputerTerminal::AIComputerTerminal()
{
}

AIComputerTerminal::~AIComputerTerminal()
{
    m_computerTerminal.StopTerminal();
}

AIMessage AIComputerTerminal::ExecuteAICommand(const AIMessage& aiCommand)
{
    if (!IsCommandSafe(aiCommand.content)) {
        AIMessage response;
        response.msgType = MessageType::ERROR_MESSAGE;
        response.source = TerminalType::COMPUTER_TO_AI;
        response.destination = TerminalType::AI_TO_HUMAN;
        response.content = "Command rejected: Potential security risk detected";
        response.messageId = aiCommand.messageId + "_rejected";
        return response;
    }
    
    wxPrintf("🖥️  Executing AI command: %s\n", aiCommand.content);
    
    // 根据内容类型处理命令
    AIMessage response;
    response.msgType = MessageType::DATA_RESPONSE;
    response.source = TerminalType::COMPUTER_TO_AI;
    response.destination = TerminalType::AI_TO_HUMAN;
    response.messageId = aiCommand.messageId + "_result";
    
    switch (aiCommand.contentType) {
        case ContentType::FILE_PATH:
            response = HandleFileOperation(aiCommand);
            break;
        case ContentType::CODE:
            response = HandleCodeGeneration(aiCommand);
            break;
        case ContentType::COMMAND:
            response = HandleSystemOperation(aiCommand);
            break;
        default:
            response = HandleSystemOperation(aiCommand);
            break;
    }
    
    return response;
}

AIMessage AIComputerTerminal::ProcessDataRequest(const AIMessage& request)
{
    AIMessage response;
    response.msgType = MessageType::DATA_RESPONSE;
    response.source = TerminalType::COMPUTER_TO_AI;
    response.destination = TerminalType::AI_TO_HUMAN;
    response.messageId = request.messageId + "_data";
    
    wxString requestType = request.metadata.count("request_type") ? 
                          request.metadata.at("request_type") : "unknown";
    
    if (requestType == "file_list") {
        wxString path = request.content.IsEmpty() ? wxGetCwd() : request.content;
        wxArrayString files;
        wxDir::GetAllFiles(path, &files, "*.cpp", wxDIR_FILES);
        wxDir::GetAllFiles(path, &files, "*.h", wxDIR_FILES);
        
        response.content = "Files in " + path + ":\n";
        for (const auto& file : files) {
            response.content += "  " + file + "\n";
        }
    } else if (requestType == "system_info") {
        response.content = "System Information:\n";
        response.content += "  Current Dir: " + wxGetCwd() + "\n";
        response.content += "  Temp Dir: " + wxFileName::GetTempDir() + "\n";
    } else {
        response.content = "Unknown data request type: " + requestType;
        response.msgType = MessageType::ERROR_MESSAGE;
    }
    
    return response;
}

AIMessage AIComputerTerminal::GetSystemStatus()
{
    AIMessage status;
    status.msgType = MessageType::STATUS_UPDATE;
    status.source = TerminalType::COMPUTER_TO_AI;
    status.destination = TerminalType::AI_TO_HUMAN;
    status.messageId = wxString::Format("status_%lld", wxGetLocalTime());
    
    status.content = "Computer System Status:\n";
    status.content += "  Terminal: " + wxString(m_computerTerminal.IsRunning() ? "Running" : "Stopped") + "\n";
    status.content += "  Current Directory: " + wxGetCwd() + "\n";
    status.content += "  Pending Commands: " + wxString::Format("%zu", m_pendingCommands.size());
    
    return status;
}

std::vector<AIMessage> AIComputerTerminal::ExecuteBatchCommands(const std::vector<AIMessage>& commands)
{
    std::vector<AIMessage> responses;
    
    for (const auto& cmd : commands) {
        if (!IsCommandSafe(cmd.content)) {
            AIMessage response;
            response.msgType = MessageType::ERROR_MESSAGE;
            response.content = "Skipped unsafe command: " + cmd.content;
            responses.push_back(response);
            continue;
        }
        
        responses.push_back(ExecuteAICommand(cmd));
        wxMilliSleep(100); // 避免过快执行
    }
    
    return responses;
}

bool AIComputerTerminal::IsCommandSafe(const wxString& command)
{
    wxString lowerCmd = command.Lower();
    
    // 危险命令列表
    const wxString dangerous[] = {
        "format", "del /", "rm -rf /", "mkfs", "dd if=",
        "chmod 777", "> /dev/sda", "| rm -rf", "&& rm -rf"
    };
    
    for (const auto& dangerousCmd : dangerous) {
        if (lowerCmd.Contains(dangerousCmd)) {
            return false;
        }
    }
    
    return true;
}

AIMessage AIComputerTerminal::HandleFileOperation(const AIMessage& command)
{
    AIMessage response;
    response.msgType = MessageType::DATA_RESPONSE;
    
    wxString operation = command.metadata.count("operation") ? 
                        command.metadata.at("operation") : "read";
    
    if (operation == "read") {
        if (wxFileExists(command.content)) {
            wxTextFile file;
            if (file.Open(command.content)) {
                response.content = "File content of " + command.content + ":\n";
                for (size_t i = 0; i < file.GetLineCount() && i < 10; i++) {
                    response.content += "  " + file[i] + "\n";
                }
                if (file.GetLineCount() > 10) {
                    response.content += "  ... (showing first 10 lines)\n";
                }
                file.Close();
            } else {
                response.msgType = MessageType::ERROR_MESSAGE;
                response.content = "Cannot open file: " + command.content;
            }
        } else {
            response.msgType = MessageType::ERROR_MESSAGE;
            response.content = "File not found: " + command.content;
        }
    } else if (operation == "write") {
        // 简化的写入操作
        response.content = "Write operation requested for: " + command.content;
    }
    
    return response;
}

AIMessage AIComputerTerminal::HandleCodeGeneration(const AIMessage& command)
{
    AIMessage response;
    response.msgType = MessageType::DATA_RESPONSE;
    response.content = "Code generation completed for: " + command.content;
    return response;
}

AIMessage AIComputerTerminal::HandleBuildOperation(const AIMessage& command)
{
    AIMessage response;
    
    if (!m_computerTerminal.IsRunning()) {
        m_computerTerminal.StartTerminal();
    }
    
    wxString output = m_computerTerminal.ExecuteCommand(command.content);
    
    response.msgType = MessageType::DATA_RESPONSE;
    response.content = "Build output:\n" + output;
    
    return response;
}

AIMessage AIComputerTerminal::HandleSystemOperation(const AIMessage& command)
{
    AIMessage response;
    
    if (!m_computerTerminal.IsRunning()) {
        m_computerTerminal.StartTerminal();
    }
    
    wxString output = m_computerTerminal.ExecuteCommand(command.content);
    
    response.msgType = MessageType::DATA_RESPONSE;
    response.content = "Command output:\n" + output;
    
    return response;
}

bool AIComputerTerminal::ContainsDangerousCommands(const wxString& command)
{
    return !IsCommandSafe(command);
}
